let stomp = null;

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    $("#send").prop("disabled", !connected);

    if (connected) {
        $("#conversation").show();
    } else {
        $("#conversation").hide();
    }

    $('#output').val('');
    $("#responses").html("");
}

var userId = 'user' + Math.floor((Math.random() * 1000) + 1);

var headers = {
    userId: userId,
    username: 'admin',
    password: 'admin'
};

function connect() {
    stomp = Stomp.over(new SockJS('http://localhost:8082/websocket-sockjs-stomp'));
//    stomp = Stomp.client("ws://localhost:8082/websocket-sockjs-stomp");

    stomp.connect(headers, function (frame) {
        setConnected(true);
        console.log('Client connected: ' + frame);

        stomp.subscribe('/app/subscribe', function (response) {
            log(response, 'table-success');
            console.log('一次性消息: ' + response);
        });

        stomp.subscribe('/user/' + userId + '/msg', function (response) {
            log(response, 'table-success');
            console.log('点对点消息: ' + response);
        });

        const subscription = stomp.subscribe('/queue/responses', function (response) {
            log(response, 'table-success');
        });

        stomp.subscribe('/queue/errors', function (response) {
            log(response, 'table-danger');
            subscription.unsubscribe({});
        });

        stomp.subscribe('/topic/periodic', function (response) {
            console.log('收到广播消息: ' + response);
            log(response, 'table-info');
        });
    });
}

function disconnect() {
    if (stomp !== null) {
        stomp.disconnect(function () {
            setConnected(false);
            console.log("Client disconnected");
        });
        stomp = null;
    }
}

function send() {
    const output = $("#output").val();
    const toUser = $("#toUser").val();
    let data = {
        userId: userId,
        username: "admin",
        payload: output,
        toUserId: toUser
    };
    console.log("head: " + JSON.stringify(data));
    const jsonStr = JSON.stringify(data);
    stomp.send("/app/request", data, output);
}

function log(response, clazz) {
    console.log("response: " + response);
    const input = response.body;
    console.log("Client received: " + input);
    $("#responses").append("<tr class='" + clazz + "'><td>当前用户：" + userId + "</td><td>" + input + "</td></tr>");
}

$(function () {
    $("form").on('submit', function (e) {
        e.preventDefault();
    });
    $("#connect").click(function () {
        connect();
    });
    $("#disconnect").click(function () {
        disconnect();
    });
    $("#send").click(function () {
        send();
    });
});
